//
//  HDOperationViewController.m
//  HDOperationProject
//
//  Created by Mirko on 15/10/30.
//  Copyright (c) 2015年 Mirko. All rights reserved.
//

#import "HDOperationViewController.h"
#import "HDOperationWebViewController.h"
#import "HDOperationDataManager.h"
#import "HDOperationActivitiesData.h"

const NSInteger kCountdownTime = 5;

@interface HDOperationViewController ()

@property (nonatomic, weak) IBOutlet UIImageView *adImageView;      // 广告图片视图
@property (nonatomic, weak) IBOutlet UIImageView *logoImageView;    // app logo图片视图

@property (nonatomic, weak) IBOutlet UILabel *timeLabel;            // 计时label

@property (nonatomic, weak) IBOutlet UIButton *skipButton;          // 跳过按钮
@property (nonatomic, weak) IBOutlet UIView *skipView;            // 跳过视图

@property (nonatomic, assign) NSInteger countdownTime;              // 倒计时时间

@property (nonatomic, strong) HDOperationActivitiesData *adInfo;

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *layoutConstraintWidth;

@property (weak, nonatomic) IBOutlet UIImageView *bottomImageView;

@end

@implementation HDOperationViewController {
    NSTimer *_timer;
}

- (void)dealloc {
    if ([_timer isValid]) {
        [_timer invalidate];
         _timer = nil;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];

}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    
    if ([_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
    self.countdownTime = 0;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidBecomeActiveNotification:)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidEnterBackgroundNotification:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];

    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                 action:@selector(pushWebViewAction:)];
    [self.adImageView addGestureRecognizer:tapGesture];
    
}

- (void)applicationDidBecomeActiveNotification:(NSNotification *)notification {
    
    
//    if (self.countdownTime <= 0) {
//        
//        UIViewController *viewCtrl = [[[UIApplication sharedApplication].delegate window] rootViewController];
//        
//        if ([viewCtrl isKindOfClass:[UINavigationController class]]) {
//            
//            UIViewController *topViewController = [(UINavigationController *)viewCtrl topViewController];
//            
//            
//            if ([topViewController isMemberOfClass:[HDOperationViewController class]]) {
//                
//                HDOperationViewController *operationViewController = (HDOperationViewController *)topViewController;
//                
//                [operationViewController closeAdWithAnimate];
//            }
//            
//            
//            NSLog(@"topViewController: %@", topViewController);
//        }
//    }
    

    [_timer setFireDate:[NSDate date]];
}

- (void)applicationDidEnterBackgroundNotification:(NSNotification *)notification {
    
    [_timer setFireDate:[NSDate distantFuture]];
}


-(void) initializeValue
{
    self.navigationController.navigationBar.hidden = YES;
    
    NSLog(@"屏幕模式s: %@", [UIScreen mainScreen].availableModes);
    NSLog(@"屏幕模式: %@", [UIScreen mainScreen].preferredMode);
    NSLog(@"屏幕尺寸: %@", NSStringFromCGSize([UIScreen mainScreen].currentMode.size));
    
    // 获取图片进行显示
    self.adInfo = [[HDOperationDataManager shareManager] needShowAdInfo];
    
    if (self.adInfo.image) {
        self.adImageView.image = self.adInfo.image;
    }
    
    // 测试
//    self.logoImageView.image = self.adInfo.image;
    
    // 是否允许关闭
    self.skipButton.hidden = !(self.adInfo.allowClose);
    
    if (self.adInfo.allowClose) {
        
        self.layoutConstraintWidth.constant = 30.0f;
    }else {
        self.layoutConstraintWidth.constant = 0.0f;
    }
    
    // 页面停留时间
    self.countdownTime = (NSInteger)self.adInfo.displayTime;
}

-(void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self initializeValue];
    
    if (self.countdownTime != 0) {
        
            // 添加定时器
            _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                      target:self
                                                    selector:@selector(countdownAction:)
                                                    userInfo:nil
                                                     repeats:YES];

            [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
            [_timer fire];
        
    }else{
        self.timeLabel.text = @"";
    }
}

#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"ShowOperationWebAction"]) {
        HDOperationWebViewController *viewController = segue.destinationViewController;
        viewController.param = (NSDictionary *) sender;
    }
}

// 跳过
- (IBAction)skipAction:(id)sender {
    
    [self closeAdWithAnimate];
    
//    if (self.finishBlock) {
//        self.finishBlock();
//    }
}

// 跳转到webView
- (void)pushWebViewAction:(UITapGestureRecognizer *)gesture {
    
    if (self.adInfo.linkUrl) {
        
        [_timer invalidate];
        
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(cancelCount) object:nil];
        
        [self performSegueWithIdentifier:@"ShowOperationWebAction" sender:@{@"param":self.adInfo.linkUrl , @"Action":[NSValue valueWithPointer:(__bridge const void *)(self.finishBlock)]}];
    }
    
}

// 倒计时
- (void)countdownAction:(NSTimer *)timer {
    NSLog(@"%@", NSStringFromSelector(_cmd));
    NSLog(@"倒计时开始...");
    
    self.timeLabel.text = [NSString stringWithFormat:@"%ld", (long)self.countdownTime];
    
    self.countdownTime -= 1;
    
    if (self.countdownTime == 0) {
        [self performSelector:@selector(cancelCount) withObject:nil afterDelay:1.0];
    }
}

-(void) cancelCount
{
    [_timer invalidate];
    
    [self closeAdWithAnimate];
    
//    if (self.finishBlock) {
//        self.finishBlock();
//    }
}

// 关闭广告
- (void)closeAdWithAnimate {
    
//    UIColor *defaultColor = ([UIApplication sharedApplication]).keyWindow.backgroundColor;
//    ([UIApplication sharedApplication]).keyWindow.backgroundColor = [UIColor whiteColor];
//    
//    [UIView animateWithDuration:0.375 animations:^{
//        
//        self.view.alpha = 0;
//        
//    } completion:^(BOOL finished) {
//        
//        if (finished) {
//            
//            ([UIApplication sharedApplication]).keyWindow.backgroundColor = defaultColor;
    
            if (self.finishBlock) {
                self.finishBlock();
            }

//        }
//    }];
}

@end
